import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import updateLocale from 'dayjs/plugin/updateLocale'
import isToday from 'dayjs/plugin/isToday'
import isYesterday from 'dayjs/plugin/isYesterday'
import duration from 'dayjs/plugin/duration'
import 'dayjs/locale/zh-cn'

dayjs.extend(relativeTime)
dayjs.extend(updateLocale)
dayjs.extend(isToday)
dayjs.extend(isYesterday)
dayjs.extend(duration)
dayjs.locale('zh-cn')
dayjs.updateLocale('zh-cn', {
	relativeTime: {
		future: '%s',
		past: '%s前',
		s: '1秒钟',
		ss: '%d秒',
		d: '1天',
		dd: '%d天',
		m: '1分钟',
		mm: '%d分钟',
		h: '1小时',
		hh: '%d小时',
		M: '1个月',
		MM: '%d个月',
		y: '1年',
		yy: '%d年'
	}
})

/**
 * 格式化时间
 * @params {string} time 时间戳
 * @params {string} format 格式 YYYY-MM-DD HH:mm
 * @returns {string} 格式化后的时间
 */
export const formatTime = (time: string, format = 'YYYY-MM-DD HH:mm:ss'): string => {
	if (!time) return '--'

	const _time = time.toString().length === 10 ? Number(time) * 1000 : time
	const formattedTime = dayjs(_time)

	if (!formattedTime.isValid()) return '--'
	return dayjs(_time).format(format)
}
